<template>
  <div class="page">
    <!-- 页面头部 -->
    <el-page-header @back="() => {}" content="房间标签管理">
      <template #content>
        <div class="page-title">
          <h2>🏷️ 房间标签管理</h2>
          <p class="page-subtitle">管理房间标签，用于分类和标识房间特性</p>
        </div>
      </template>
      <template #extra>
        <el-button type="primary" @click="showAddModal = true">
          <el-icon><Plus /></el-icon>
          添加标签
        </el-button>
      </template>
    </el-page-header>

    <!-- 内容卡片 -->
    <el-card class="content-card">
      <!-- 搜索和筛选 -->
      <template #header>
        <div class="search-section">
          <el-input
            v-model="searchQuery"
            placeholder="搜索标签名称..."
            class="search-input"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
        </div>
      </template>

      <!-- 标签列表 -->
      <div class="labels-grid">
        <el-card 
          v-for="label in filteredLabels" 
          :key="label.id"
          class="label-card"
          shadow="hover"
        >
          <template #header>
            <div class="label-header">
              <div class="label-info">
                <span class="label-name">{{ label.name }}</span>
              </div>
              <div class="label-actions">
                <el-button size="small" @click="editLabel(label)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button size="small" type="danger" @click="deleteLabel(label)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </template>
          
          
        </el-card>
      </div>

      
    </el-card>

    <!-- 添加/编辑标签对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="showAddModal ? '添加标签' : '编辑标签'"
      width="500px"
      @close="closeModal"
    >
      <el-form
        ref="formRef"
        :model="labelForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input
            v-model="labelForm.name"
            placeholder="如：向阳、安静、近卫生间"
            clearable
          />
        </el-form-item>
        
      </el-form>
      
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="saveLabel">
          {{ showAddModal ? '添加' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Edit, Delete } from '@element-plus/icons-vue'
import { 
  queryRoomLabelAPI, 
  addRoomLabelAPI, 
  updateRoomLabelAPI, 
  deleteRoomLabelAPI 
} from '@/apis/roomLabelAPI'

// 响应式数据
const searchQuery = ref('')
 
// 无分页展示
const showAddModal = ref(false)
const showEditModal = ref(false)
const editingLabel = ref(null)
const formRef = ref()

// 对话框显示状态
const dialogVisible = computed({
  get: () => showAddModal.value || showEditModal.value,
  set: (value) => {
    if (!value) {
      closeModal()
    }
  }
})

// 标签表单
const labelForm = ref({
  name: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 1, max: 20, message: '标签名称长度在 1 到 20 个字符', trigger: 'blur' }
  ]
}

// 标签数据
const labels = ref([])
const loading = ref(false)

// 计算属性
const filteredLabels = computed(() => {
  let filtered = labels.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(label => 
      label.name.toLowerCase().includes(query)
    )
  }

  

  return filtered
})

// 无分页所需的总数可按需使用：filteredLabels.value.length

// 方法

const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const editLabel = (label) => {
  editingLabel.value = label
  labelForm.value = { name: label.name }
  showEditModal.value = true
}

const deleteLabel = async (label) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除标签 "${label.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    const res = await deleteRoomLabelAPI(label.id)
    if (res && res.code === 0) {
      ElMessage.success('删除成功')
      await refreshLabels()
    } else {
      ElMessage.error(res?.msg || '删除失败')
    }
  } catch (e) {
    // 取消或异常
  }
}

const saveLabel = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    if (showAddModal.value) {
      const res = await addRoomLabelAPI(labelForm.value)
      if (res && res.code === 0) {
        ElMessage.success('添加成功')
        await refreshLabels()
        closeModal()
      } else {
        ElMessage.error(res?.msg || '添加失败')
      }
    } else {
      if (!editingLabel.value || !editingLabel.value.id) {
        ElMessage.error('未选择要编辑的标签')
        return
      }
      const res = await updateRoomLabelAPI({ id: editingLabel.value.id, name: labelForm.value.name })
      if (res && res.code === 0) {
        ElMessage.success('保存成功')
        await refreshLabels()
        closeModal()
      } else {
        ElMessage.error(res?.msg || '保存失败')
      }
    }
  } catch (error) {
    // 校验失败或异常
  }
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  editingLabel.value = null
  labelForm.value = {
    name: ''
  }
  // 清除表单验证
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const refreshLabels = async () => {
  loading.value = true
  try {
    const res = await queryRoomLabelAPI()
    if (res && res.code === 0) {
      labels.value = res.data
    } else {
      ElMessage.error(res?.msg || '获取标签数据失败')
    }
  } catch (e) {
    ElMessage.error('获取标签数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  await refreshLabels()
})
</script>

<style scoped>
.page {
  padding: 20px;
}

.page-title h2 {
  font-size: 1.875rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
}

.page-subtitle {
  font-size: 0.875rem;
  margin: 0;
  color: #666;
}

.content-card {
  margin-top: 20px;
}

.search-section {
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-input {
  width: 300px;
}

 

.labels-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.label-card {
  margin-bottom: 0;
}

.label-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 12px;
}

.label-info {
  flex: 1;
}

.label-name {
  font-size: 1.125rem;
  font-weight: 600;
  display: block;
  margin-bottom: 8px;
}

.label-actions {
  display: flex;
  gap: 8px;
}

 
</style>
